package com.producer.config;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.producer.model.Result;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.springframework.http.HttpStatus;
import xiaohua.utils.json.JacksonUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author Liunh
 */
@Slf4j
public class FeignException implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        try {
            String json = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            if (StringUtils.isBlank(json)) {
                return null;
            }
            Map<String, Object> map = JacksonUtil.jsonToMap(json, Object.class);
            Result<String> result = new Result<>();
            if (null != map && map.size() > 0) {
                result.setCode((int) map.get("code"));
                result.setMsg(String.valueOf(map.get("msg")));
            }
            result.setData(json);

            if (result.getCode() != HttpStatus.OK.value()) {
                ServiceException serviceException = new ServiceException(result.toString());
                exception = new HystrixBadRequestException(result.getMsg(), serviceException);
            }
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
        return exception;
    }
}
